﻿using System.Collections.Generic;
using System.IO;

class Ex5FindWordInFile
{
    static void Main()
    {
        string searchedDirectory = @"e:\downloads\";
        string searchedPhrase = "secret";

        SearchForPhrase(searchedDirectory, searchedPhrase);
    }

    private static void SearchForPhrase(string searchedDirectory, string searchedPhrase)
    {
        DirectoryInfo root = new DirectoryInfo(searchedDirectory);
        List<string> hits = new List<string>();
        var files = root.GetFiles("*.txt", SearchOption.AllDirectories);
        foreach (var file in files)
        {
            SearchInFile(file, searchedPhrase, ref hits);
        }
        if (hits.Count > 0)
        {
            using (StreamWriter writer = new StreamWriter(@"..\..\results.txt"))
            {
                hits.ForEach(x => writer.WriteLine(x));
            }
        }
    }

    private static void SearchInFile(FileInfo file, string searchedPhrase, ref List<string> hits)
    {
        using (StreamReader reader = new StreamReader(file.FullName))
        {
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                if (line.Contains(searchedPhrase))
                {
                    hits.Add(file.FullName);
                    hits.Add(line);
                    break;
                }
            }
        }
    }
}

